package com.work.yshop.mvp.presenter;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;

import com.work.yshop.model.Product;
import com.work.yshop.mvp.contract.SearchResultsContract;
import com.work.yshop.utils.ProductDataUtils;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 搜索结果页面的Presenter实现
 */
public class SearchResultsPresenter implements SearchResultsContract.Presenter {

    private WeakReference<SearchResultsContract.View> viewRef;
    private Context context;
    private List<Product> searchResults;
    private HomePresenter homePresenter;
    private final Handler handler = new Handler(Looper.getMainLooper());
    
    public SearchResultsPresenter(Context context) {
        this.context = context;
        this.searchResults = new ArrayList<>();
        // 创建HomePresenter实例，用于获取商品数据
        this.homePresenter = new HomePresenter(context);
    }

    @Override
    public void attachView(SearchResultsContract.View view) {
        viewRef = new WeakReference<>(view);
        // 页面创建时加载所有商品
        loadAllProducts();
    }

    @Override
    public void detachView() {
        if (viewRef != null) {
            viewRef.clear();
            viewRef = null;
        }
    }
    
    /**
     * 加载所有商品
     */
    public void loadAllProducts() {
        if (getView() == null) return;
        
        getView().showLoading();
        
        // 模拟网络延迟
        handler.postDelayed(() -> {
            // 从HomePresenter获取所有商品数据
            List<Product> allProducts = homePresenter.getAllProducts();
            
            // 如果HomePresenter中没有数据，则使用统一的模拟数据源
            if (allProducts.isEmpty()) {
                allProducts = ProductDataUtils.getMockProductData();
            }
            
            // 保存搜索结果
            searchResults = new ArrayList<>(allProducts);
            
            if (getView() == null) return;
            
            getView().hideLoading();
            
            if (searchResults.isEmpty()) {
                getView().showEmptyResults();
            } else {
                getView().showSearchResults(searchResults);
            }
        }, 500);
    }

    @Override
    public void searchProducts(String keyword) {
        if (getView() == null) return;
        
        // 如果关键词为空，显示所有商品
        if (keyword == null || keyword.trim().isEmpty()) {
            loadAllProducts();
            return;
        }
        
        getView().showLoading();
        
        // 模拟网络延迟
        handler.postDelayed(() -> {
            // 从HomePresenter获取所有商品数据
            List<Product> allProducts = homePresenter.getAllProducts();
            
            // 如果HomePresenter中没有数据，则使用统一的模拟数据源
            if (allProducts.isEmpty()) {
                allProducts = ProductDataUtils.getMockProductData();
            }
            
            // 根据关键词搜索商品
            searchResults = allProducts.stream()
                .filter(product -> 
                    product.getName().toLowerCase().contains(keyword.toLowerCase()) || 
                    (product.getDescription() != null && product.getDescription().toLowerCase().contains(keyword.toLowerCase())))
                .collect(Collectors.toList());
            
            if (getView() == null) return;
            
            getView().hideLoading();
            
            if (searchResults.isEmpty()) {
                getView().showEmptyResults();
            } else {
                getView().showSearchResults(searchResults);
            }
        }, 500);
    }
    
    @Override
    public void sortByComprehensive() {
        if (getView() == null || searchResults.isEmpty()) return;
        
        // 综合排序：默认顺序，不做特殊处理
        getView().showSearchResults(searchResults);
    }

    @Override
    public void sortBySales() {
        if (getView() == null || searchResults.isEmpty()) return;
        
        // 按销量排序（从高到低）
        List<Product> sortedList = new ArrayList<>(searchResults);
        Collections.sort(sortedList, (p1, p2) -> p2.getSalesCount() - p1.getSalesCount());
        
        getView().showSearchResults(sortedList);
    }

    @Override
    public void sortByPrice() {
        if (getView() == null || searchResults.isEmpty()) return;
        
        // 按价格排序（从低到高）
        List<Product> sortedList = new ArrayList<>(searchResults);
        Collections.sort(sortedList, Comparator.comparingDouble(Product::getPrice));
        
        getView().showSearchResults(sortedList);
    }
    
    /**
     * 获取当前绑定的View
     */
    private SearchResultsContract.View getView() {
        return viewRef != null ? viewRef.get() : null;
    }
} 